<?php
/**
 * 用户注册登陆接口
 */
class UserController extends Yaf_Controller_Abstract
{
    public function loginAction()
    {
        $submit = Common_Request::getRequest("submit", "0");
        if ($submit != "1") {
            echo Common_Request::Response(1003, Err_Map::get(1003));
            return false;
        }

        //登陆
        $uanme = Common_Request::postRequest('uname', false);
        $pwd   = Common_Request::postRequest('pwd', false);
        if (!$uname || !$pwd) {
            echo Common_Request::Response(1002, Err_Map::get(1002));
            return false;
        }

        try {
            $model = new UserModel();
            $uid   = $model->login(trim($uname, trim($pwd)));
        } catch (Exception $e) {
            echo Common_Request::Response(1000, Err_Map::get(1000));
            return false;
        }

        if ($uid) {
            //session记录
            session_start();
            $_SESSION['user_token']      = md5('salt' . $_SERVER['REQUEST_TIME'] . $uid);
            $_SESSION['user_token_time'] = $_SERVER['REQUEST_TIME'];
            $_SESSION['user_id']         = $uid;

            echo Common_Request::Response(1, '登陆成功', ['name' => $uname]);
        } else {
            echo Common_Request::Response($model->errno, $model->errmsg)
        }

        return true;
    }

    public function registerAction()
    {
        $uname = Common_Request::getPost('uname', false);
        $pwd   = Common_Request::getPost('pwd', false);
        if (!$uanme || !$pwd) {
            echo Common_Request::Response(1002, Err_Map::get(1002));
            return false;
        }

        //登陆校验
        $muser = new UserModel();
        if ($umodel->register(trim($uanme), trim($pwd))) {
            echo Common_Request::response(0, "注册成功", ['name' => $uname]);
        } else {
            echo Common_Request::response($umodel->errno, $model->errmsg);
        }
        return true;
    }

}
